import Fly from "flyio/dist/npm/wx";
var util = require("./util.js");

const request = new Fly();
const errorPrompt = (err) => {
  if (err.code == 401) {
    util.cleanLoginInfo();
  } else {
    let reg = /.*[\u4e00-\u9fa5]+.*$/;
    if (!reg.test(err.msg)) {
      err.msg = "网络请求错误，请稍候再试";
    }
    util.showToast(err.msg);
  }
};

request.interceptors.request.use((request) => {
  if (!request.hideLoading) {
	  //设置loading
    let requestLodingType = util.requestLodingType;
    if (requestLodingType) {
      uni.showLoading({
        mask: requestLodingType == "mask",
        title: requestLodingType == "mask" ? "请稍候" : "加载中",
      });
    }
  }
  util.requestLodingType = "mask";

  //请求头
  request.headers = {
    "content-type": "application/json",
    roleId: uni.getStorageSync("role") || "",
  };
  let token = uni.getStorageSync("token");
  if (token) {
    request.headers["Authorization"] = "Bearer " + token;
  }
  //添加url默认前缀
  if (!request.cancelPrefix) {
    request.url = request.urlPrefix + request.url;
  }
  return request;
});

request.interceptors.response.use(
  (response, promise) => {
    uni.hideLoading();
    uni.hideToast();
    if (response.data.code != 200) {
      errorPrompt(response.data);
    }
    return promise.resolve(response.data);
  },
  (err, promise) => {
    uni.hideLoading();
    uni.hideToast();
    errorPrompt(err.response.data);
    return promise.reject(err);
  }
);

export default request;
